/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Playlist_Management;

/**
 *
 * @author GeorgeD
 */

import Converters.DateConverter;
import Main_menu.MainMenu;
import java.sql.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.ListSelectionModel;
import Radiostation_POJOS.Song;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.EntityManager;
import Radiostation_POJOS.PlaylistSongs;
import Radiostation_POJOS.Playlist;
import javax.persistence.NoResultException;

public class PlayListManagementForm extends javax.swing.JFrame {    
    private PlayListArchive PlayList_Archive;   
    
    public PlayListManagementForm(PlayListArchive PlayList_Archive, Playlist playlist) {
        this.PlayList_Archive = PlayList_Archive;
        initComponents();
        setLocationRelativeTo(null);//για την εμφάνιση του παραθύρου στο κέντρο
        this.PlayListManageTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        Radiostation_ProjectPUEntityManager = java.beans.Beans.isDesignTime() ? null : javax.persistence.Persistence.createEntityManagerFactory("Radiostation_ProjectPU").createEntityManager();
        playlist1 = this.PlayList_Archive.getPlaylist1();
        query1 = Radiostation_ProjectPUEntityManager.createQuery("SELECT NEW Playlist_Management.PlayListSongMeta(sng, art, mcg) FROM Song sng JOIN sng.playlistSongList plsl JOIN plsl.playlist pl JOIN sng.albumId alb LEFT JOIN alb.musicgroup mcg LEFT JOIN alb.artist art WHERE pl.playlistId = " + this.PlayList_Archive.getPlaylist1().getPlaylistId());
        list1 = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(query1.getResultList());
        dateConverter21 = new converters.DateConverter2();
        jLabel2 = new javax.swing.JLabel();
        txt_playlistdesc = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        txt_playlistcreationdate = new javax.swing.JTextField();
        jLabel8 = new javax.swing.JLabel();
        SaveBtn = new javax.swing.JButton();
        CancelBtn = new javax.swing.JButton();
        DeleteBtn = new javax.swing.JButton();
        AddBtn = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        PlayListManageTable = new javax.swing.JTable(new PlayListActions(list1));
        ErrorMessage = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setTitle("Φόρμα Διαχείρισης Λίστας");

        jLabel2.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel2.setText("Περιγραφή:");

        txt_playlistdesc.setHorizontalAlignment(javax.swing.JTextField.CENTER);

        org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, playlist1, org.jdesktop.beansbinding.ELProperty.create("${name}"), txt_playlistdesc, org.jdesktop.beansbinding.BeanProperty.create("text"), "b1");
        bindingGroup.addBinding(binding);

        txt_playlistdesc.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txt_playlistdescActionPerformed(evt);
            }
        });

        jLabel6.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel6.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel6.setText("Ημερ. Δημιουργίας (ΗΗ/ΜΜ/ΕΕΕΕ):");
        jLabel6.setToolTipText("");

        txt_playlistcreationdate.setHorizontalAlignment(javax.swing.JTextField.CENTER);

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, playlist1, org.jdesktop.beansbinding.ELProperty.create("${creationdate}"), txt_playlistcreationdate, org.jdesktop.beansbinding.BeanProperty.create("text"), "b2");
        binding.setConverter(dateConverter21);
        bindingGroup.addBinding(binding);

        txt_playlistcreationdate.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txt_playlistcreationdateActionPerformed(evt);
            }
        });

        jLabel8.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel8.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel8.setText("Λίστα Τραγουδιών:");

        SaveBtn.setText("Αποθήκευση");
        SaveBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                SaveBtnActionPerformed(evt);
            }
        });

        CancelBtn.setText("Ακύρωση");
        CancelBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CancelBtnActionPerformed(evt);
            }
        });

        DeleteBtn.setText("Διαγραφή");
        DeleteBtn.setToolTipText("");
        DeleteBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                DeleteBtnActionPerformed(evt);
            }
        });

        AddBtn.setText("Εισαγωγή");
        AddBtn.setToolTipText("");
        AddBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                AddBtnActionPerformed(evt);
            }
        });

        
        jScrollPane1.setViewportView(PlayListManageTable);

        ErrorMessage.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        ErrorMessage.setForeground(new java.awt.Color(255, 0, 0));
        ErrorMessage.setToolTipText("");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(ErrorMessage, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel6)
                            .addComponent(jLabel8)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel2)
                                .addGap(1, 1, 1)))
                        .addGap(2, 2, 2)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(AddBtn)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(DeleteBtn)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(SaveBtn)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(CancelBtn)
                                .addGap(0, 0, Short.MAX_VALUE))
                            .addComponent(txt_playlistcreationdate)
                            .addComponent(txt_playlistdesc))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txt_playlistdesc, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txt_playlistcreationdate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel8)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 181, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(4, 4, 4)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(DeleteBtn)
                    .addComponent(AddBtn)
                    .addComponent(SaveBtn)
                    .addComponent(CancelBtn))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(ErrorMessage, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void txt_playlistdescActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txt_playlistdescActionPerformed
        // TODO add your handling code here:
        
    }//GEN-LAST:event_txt_playlistdescActionPerformed

    private void txt_playlistcreationdateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txt_playlistcreationdateActionPerformed
        // TODO add your handling code here:
        
    }//GEN-LAST:event_txt_playlistcreationdateActionPerformed

    private void SaveBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SaveBtnActionPerformed
        // TODO add your handling code here:
        ErrorMessage.setText("");
        String creation_date = "";
        DateConverter convert = new DateConverter();
        creation_date = convert.Dateconverter2(txt_playlistcreationdate.getText());
        if (convert.flag == true){               
        if( !txt_playlistdesc.getText().trim().equalsIgnoreCase("") && !txt_playlistcreationdate.getText().trim().equalsIgnoreCase("")){            
            if(CheckSongDuration()){
                if(CheckSongExist()){
                    this.playlist1.setName(txt_playlistdesc.getText());                    
                    
                    try{
                        java.util.Date date = new SimpleDateFormat("dd/MM/yyyy").parse(creation_date);
                        this.playlist1.setCreationdate(date);
                        
                        List<Song> song_list_new = GetNewSongs();
                        List<Song> song_list_old = GetOldSongs(); 

                        if( song_list_new.size() > 0 ){                            
                            List<PlaylistSongs> playlistSongs = new ArrayList<>();
                            for(Song song:song_list_new){
                                PlaylistSongs playlistSong = new PlaylistSongs();
                                playlistSong.setPlaylist(playlist1);
                                playlistSong.setSong(song);
                                this.PlayList_Archive.getEntityManager1().persist(playlistSong);
                                playlistSongs.add(playlistSong);
                            }
                            
                            List<PlaylistSongs> allPlaylistSongs = playlistSongs;
                            if( playlist1.getPlaylistSongList() != null && !playlist1.getPlaylistSongList().isEmpty() ){
                                allPlaylistSongs.addAll(playlist1.getPlaylistSongList());
                            }
                            this.playlist1.setPlaylistSongList(allPlaylistSongs);
                        }                
        
                        this.PlayList_Archive.getEntityManager1().persist(this.playlist1);
                        this.PlayList_Archive.getList1().set(this.PlayList_Archive.getList1().indexOf(playlist1), playlist1);
                        this.PlayList_Archive.setEnabled(true);
                        this.PlayList_Archive.getEntityManager1().getTransaction().commit();
                        this.PlayList_Archive.getEntityManager1().getTransaction().begin();
                        dispose();
                    } catch(ParseException e){                    
                        ErrorMessage.setText("Η Ημερ. Κυκλοφορίας θα πρέπει να έχει την μορφή ΗΗ/ΜΜ/ΕΕΕΕ (ΗΗ:Ημέρα, ΜΜ:Μήνας, ΕΕΕΕ:Έτος)");
                    }
                } else {                
                    ErrorMessage.setText("Δεν επιτρέπονται διπλο-εισαγωγές στην Λίστα");
                }
            }else {
                ErrorMessage.setText("Η Λίστα θα πρέπει να περιέχει Τραγούδια συνολικής διάρκειας τουλάχιστον 30 λεπτά");
            }            
        } else {            
            ErrorMessage.setText("Κάποιο ή κάποια από τα απαιτούμενα πεδία δεν έχουν συμπληρωθεί");
        }
        }else{
            ErrorMessage.setText("Η Ημερ. Κυκλοφορίας θα πρέπει να έχει την μορφή ΗΗ/ΜΜ/ΕΕΕΕ (ΗΗ:Ημέρα, ΜΜ:Μήνας, ΕΕΕΕ:Έτος)");
        }
        
        
    }//GEN-LAST:event_SaveBtnActionPerformed

    private void CancelBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CancelBtnActionPerformed
        // TODO add your handling code here:
        PlayList_Archive.setEnabled(true);
        dispose();
    }//GEN-LAST:event_CancelBtnActionPerformed

    private void DeleteBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_DeleteBtnActionPerformed
         // TODO add your handling code here:
        ErrorMessage.setText("");
        int index = PlayListManageTable.getSelectedRow();
        if(index >= 0){
            PlayListActions songTableModel = (PlayListActions)this.PlayListManageTable.getModel();
            List<Object[]> dataFromTable = songTableModel.getSongs();
            Integer songId = (Integer)dataFromTable.get(index)[0];
            try{
                PlaylistSongs playlistSongToBeDeleted = this.PlayList_Archive.getEntityManager1()
                        .createNamedQuery("PlaylistSongs.findBySongIdAndPlaylist", PlaylistSongs.class)
                        .setParameter("playlist", playlist1)
                        .setParameter("song", songId)
                        .getSingleResult();
                songTableModel.deleteRow(index);
//                this.PlayList_Archive.getEntityManager1().remove(playlistSongToBeDeleted);                
//                this.PlayList_Archive.getEntityManager1().getTransaction().commit();
//                this.PlayList_Archive.getEntityManager1().getTransaction().begin();
//                this.PlayList_Archive.getEntityManager1().refresh(this.playlist1);
            } catch(NoResultException e){
                songTableModel.deleteRow(index);
            }
        } else {
            ErrorMessage.setText("Πρέπει να επιλέξετε ένα Τραγούδι από τον παραπάνω πίνακα");
        }
        
    }//GEN-LAST:event_DeleteBtnActionPerformed

    private void AddBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AddBtnActionPerformed
        // TODO add your handling code here:
        PlayListActions model = (PlayListActions)PlayListManageTable.getModel();
        PlayListSongSearch st = new PlayListSongSearch(this, model);
        st.setVisible(true);
        this.setEnabled(false);
    }//GEN-LAST:event_AddBtnActionPerformed

    /**
     * @param args the command line arguments
     */
    
    
    private List<Song> GetNewSongs() {
        PlayListActions playlistSongTableModel = (PlayListActions) this.PlayListManageTable.getModel();
        int songsAdded = playlistSongTableModel.getSongsAdded();
        List<Object[]> dataFromTable = playlistSongTableModel.getSongs();
        List<Song> song_list = new ArrayList<>();
        for (int i = dataFromTable.size() - 1; i >= dataFromTable.size() - songsAdded; i--) {
            Object[] data = dataFromTable.get(i);            
            Song song = this.PlayList_Archive.getEntityManager1()
                    .createNamedQuery("Song.findBySongId", Song.class)
                    .setParameter("songId", (Integer)data[0])
                    .getSingleResult();
            song_list.add(song);            
        }
        
        return song_list;
    }
    
    private List<Song> GetOldSongs() {
        List<Song> song_list = new ArrayList<>();
        for(PlayListSongMeta PlayList_SongMeta:list1) {            
            Song song = this.PlayList_Archive.getEntityManager1()
                .createNamedQuery("Song.findBySongId", Song.class)
                .setParameter("songId", PlayList_SongMeta.getSong().getSongId())
                .getSingleResult();
            song_list.add(song);
        }
        
        return song_list;
    }    
    
    private boolean CheckSongDuration(){
        float minutes = 0;        
        PlayListActions songTableModel = (PlayListActions)this.PlayListManageTable.getModel();
        List<Object[]> dataFromTable = songTableModel.getSongs();
        
        for (int i = 0; i <= dataFromTable.size()-1; i++) {
            Object[] data = dataFromTable.get(i); 
            minutes += Float.parseFloat(dataFromTable.get(i)[3].toString());            
        }
        
        return (minutes >= 30.00)?true:false;
    }
    
    private boolean CheckSongExist() {
        PlayListActions playlistSongTableModel = (PlayListActions) this.PlayListManageTable.getModel();
        List<Object[]> dataFromTable = playlistSongTableModel.getSongs();
        Set<Integer> uniqueSongs = new HashSet<>();
        for (int i = 0; i < dataFromTable.size(); i++) {
            Object[] data = dataFromTable.get(i);
            uniqueSongs.add((Integer) data[0]);
        }        
        return (dataFromTable.size() == uniqueSongs.size()) ? true : false;
    }
    
    public PlayListActions getModelPlayListManageTable() {
        return (PlayListActions)PlayListManageTable.getModel();
    }

    public EntityManager GetRadiostation_ProjectPUEntityManager() {
        return Radiostation_ProjectPUEntityManager;
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton AddBtn;
    private javax.swing.JButton CancelBtn;
    private javax.swing.JButton DeleteBtn;
    private javax.swing.JLabel ErrorMessage;
    private javax.swing.JTable PlayListManageTable;
    private javax.persistence.EntityManager Radiostation_ProjectPUEntityManager;
    private javax.swing.JButton SaveBtn;
    private converters.DateConverter2 dateConverter21;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JScrollPane jScrollPane1;
    private java.util.List<Playlist_Management.PlayListSongMeta> list1;
    private Radiostation_POJOS.Playlist playlist1;
    private javax.persistence.Query query1;
    private javax.swing.JTextField txt_playlistcreationdate;
    private javax.swing.JTextField txt_playlistdesc;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables

}
